package com.abcode.thymeleaf.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashSet;
import java.util.Set;

@Slf4j
@Component
public class WebSocketHandler extends TextWebSocketHandler {

    // 存储当前活跃的会话
    private static final Set<WebSocketSession> sessions = new HashSet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 连接建立时添加到 sessions 集合
        sessions.add(session);
        System.out.println("连接建立：" + session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 接收到消息时处理逻辑
        System.out.println("接收到消息：" + message.getPayload());
        session.sendMessage(new TextMessage("服务端响应：" + message.getPayload()));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 连接关闭时从 sessions 集合移除
        sessions.remove(session);
        System.out.println("连接关闭：" + session.getId());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 处理连接错误
        System.err.println("连接出错：" + exception.getMessage());
        sessions.remove(session);
    }

    // 发送心跳消息
    public void sendHeartbeat() {
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage("heartbeat"));
                    log.info("发送心跳消息给客户端：" + session.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}